package com.tongtech.space.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.tongtech.space.common.pojo.Result;
import com.tongtech.space.common.pojo.UserInfo;
import com.tongtech.space.common.utils.CommonUtils;
import com.tongtech.space.common.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

import static com.tongtech.space.common.constants.Constants.SESSION_USER_INFO;

/**
 * 登录验证拦截器
 *
 * @author jinjiayu
 * @since 2021/1/14
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private UserHolder userHolder;

    @Resource
    RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) {
        String ip = CommonUtils.getIpAddress(request);
        String url = request.getRequestURI();
        log.info("登录验证拦截器---请求接口为:" + url + ", 请求者IP为:" + ip);

        // 1.获取当前session,如果session为空则会话不存在或已失效,返回403错误或跳转到登录地址等
        HttpSession session = request.getSession(false);
        if (session == null) {
            returnAuthErrorStr(response, "登录会话已失效!", HttpServletResponse.SC_FORBIDDEN);
            return false;
        }

        // 2.如果会话有效则获取当前会话中的userInfo对象,放入ThreadLocal对象中
        UserInfo userInfo = (UserInfo)session.getAttribute(SESSION_USER_INFO);
        UserHolder.setCurrentUser(userInfo);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) {
        if(response.getStatus() == HttpServletResponse.SC_NOT_FOUND){
            returnAuthErrorStr(response, "此接口不存在!", HttpServletResponse.SC_NOT_FOUND);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        userHolder.clean();
    }

    /**
     * 返回错误信息
     *
     * @param response errorStr
     * @author jinjiayu
     */
    private void returnAuthErrorStr(HttpServletResponse response, String errorStr, int httpCode) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            response.setStatus(httpCode);
            PrintWriter writer = response.getWriter();
            Result<?> fail = Result.fail(errorStr);
            writer.print(JSON.toJSONString(fail));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
